<template>
  <div>
    <!-- 面包屑到导航区 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片试图 -->
    <el-card>
      <!-- 添加角色按钮区域 -->
      <el-row>
        <el-col :span="1">
          <el-button type="primary" @click="addRolesDialog">添加角色</el-button>
        </el-col>
      </el-row>
      <!-- 角色列表展示区域 -->
      <el-table :data="roleList" style="width: 100%" border stripe>
        <el-table-column type="expand">
          <template slot-scope="scope">
            <el-row
              v-for="(item1, index) in scope.row.children"
              :key="item1.id"
              :class="['bdtop', index === 0 ? 'bdtop' : '', 'vcenter']"
            >
              <!-- 渲染一级权限 -->
              <el-col :span="5" class="vc">
                <el-tag
                  closable
                  @close="removeRightById(scope.row, item1.id)"
                  >{{ item1.authName }}</el-tag
                >
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 渲染二级三级权限 -->
              <el-col :span="19">
                <el-row
                  v-for="(item2, index2) in item1.children"
                  :key="item2.id"
                  :class="['bdtop', index2 === 0 ? '' : 'botop', 'vcenter']"
                >
                  <el-col :span="6">
                    <el-tag
                      type="success"
                      closable
                      @close="removeRightById(scope.row, item2.id)"
                      >{{ item2.authName }}</el-tag
                    >
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <el-col :span="18">
                    <el-tag
                      type="warning"
                      v-for="item3 in item2.children"
                      :key="item3.id"
                      closable
                      @close="removeRightById(scope.row, item3.id)"
                      >{{ item3.authName }}</el-tag
                    >
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column type="index"></el-table-column>
        <el-table-column prop="roleName" label="角色名称"></el-table-column>
        <el-table-column prop="roleDesc" label="角色描述"></el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="editInfoDialog(scope.row.id)"
              >编辑</el-button
            >
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="removeRoleById(scope.row.id)"
              >删除</el-button
            >
            <el-button
              type="warning"
              icon="el-icon-setting"
              size="mini"
              @click="addRightsDialog(scope.row)"
              >分配权限</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 添加角色的对话框 -->
    <el-dialog
      title="添加用户"
      :visible.sync="addRolesDialogVisible"
      width="50%"
      @close="edidDialogClosed"
    >
      <el-form
        :model="addForm"
        :rules="addRoleFormrules"
        ref="addRoleFormRef"
        label-width="80px"
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="addForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="addForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="addRolesDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addRole">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 编辑对话框 -->
    <el-dialog title="编辑修改" :visible.sync="editDialogVisible" width="50%">
      <el-form
        :model="addForm"
        ref="addRoleFormRef"
        label-width="80px"
        @close="edidDialogClosed"
      >
        <el-form-item label="角色名称">
          <el-input v-model="editForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述">
          <el-input v-model="editForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editRoleInfo">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 分配权限对话框 -->
    <el-dialog
      title="分配权限"
      :visible.sync="rightDialogState"
      width="50%"
      @close="setRightDialogClosed"
      >
      <!-- 树形控件 -->
      <el-tree
        :data="rightList"
        :props="treeProps"
        show-checkbox
        node-key="id"
        default-expand-all
        :default-checked-keys="defKeys"
        ref="treeRef"
      >
      </el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="rightDialogState = false">取 消</el-button>
        <el-button
         type="primary"
         @click="allotRight"
        >
          确 定
          </el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      // 所有权限数据
      rightList: [],
      roleList: [],
      editDialogVisible: false,
      editForm: [],
      addRolesDialogVisible: false,
      addForm: {
        roleName: '',
        roleDesc: '',
      },
      addRoleFormrules: {
        roleName: [
          { required: true, message: '请输入角色名称', trigger: 'blur' },
        ],
        roleDesc: [
          { required: true, message: '请输入角色描述', trigger: 'blur' },
        ],
      },
      rightDialogState: false,
      // 要展示的树形控件的文字
      treeProps: {
        label: 'authName',
        children: 'children',
      },
      // 默认选中的树形节点id
      defKeys: [],
      // 当前即将分配权限的角色id
      roleId: ''
    }
  },
  created() {
    this.getRolesList()
  },
  methods: {
    // 获取所有用户列表数据
    async getRolesList() {
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) {
        return this.$message.error('获取角色列表失败')
      }
      this.roleList = res.data
    },
    // 弹出编辑框
    async editInfoDialog(id) {
      this.editDialogVisible = true
      const { data: res } = await this.$http.get('roles/' + id, {
        params: {},
      })
      this.editForm = res.data
      console.log(this.editForm)
    },
    // 弹出添加用户框
    addRolesDialog() {
      this.addRolesDialogVisible = true
    },
    // 点击确定完成数据的添加以及刷新数据
    addRole() {
      this.$refs.addRoleFormRef.validate(async (valid) => {
        if (!valid) {
          return this.$message.error('输入信息有误，请检查后再试')
        }
        const { data: res } = await this.$http.post('roles', this.addForm)
        // 实现添加用户的网络请求
        if (res.meta.status !== 201) {
          this.$message.error('添加用户失败')
        }
        this.$message.success('添加成功')
        this.addRolesDialogVisible = false
        this.getRolesList()
      })
    },
    // 关闭框后更新操作
    edidDialogClosed() {
      this.$refs.addRoleFormRef.resetFields()
    },
    // 修改用户信息后提交
    editRoleInfo() {
      this.$refs.addRoleFormRef.validate(async (valid) => {
        if (!valid) {
          return this.$message.error('信息有误')
        }
        // 修改用户信息
        const { data: res } = await this.$http.put(
          'roles/' + this.editForm.roleId,
          {
            roleName: this.editForm.roleName,
            roleDesc: this.editForm.roleDesc,
          }
        )
        console.log(res)
        if (res.meta.status !== 200) {
          return this.$message.error('更新数据失败')
        }
        // 关闭对话框
        this.editDialogVisible = false
        // 刷新数据列表
        this.getRolesList()
        // 提示信息
        this.$message.success('数据修改正确')
      })
    },
    // 根据id删除用户数据
    async removeRoleById(id) {
      // 弹出一个框，用来提示用户是否确定删除
      const confirmResult = await this.$confirm(
        '此操作将永久删除该用户, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      ).catch((err) => err)
      if (confirmResult !== 'confirm') {
        return this.$message.info('已取消删除')
      }
      const { data: res } = await this.$http.delete('roles/' + id)
      if (res.meta.status !== 200) {
        this.$message.error('删除用户失败')
      }
      this.$message.success('删除用户成功')
      this.getRolesList()
    },
    // 标签删除
    async removeRightById(role, rightId) {
      const confirmResult = await this.$confirm(
        '此操作将永久删除该用户权限, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      ).catch((err) => err)
      if (confirmResult !== 'confirm') {
        return this.$message.info('已取消删除')
      }
      const { data: res } = await this.$http.delete(
        `roles/${role.id}/rights/${rightId}`
      )
      if (res.meta.status !== 200) {
        this.$message.error('删除用户权限失败')
      }
      this.$message.success('删除用户权限成功')
      role.children = res.data
    },
    // 展示分配权限
    async addRightsDialog(role) {
      this.roleId = role.id
      // 获取所有权限的数据
      const { data: res } = await this.$http.get('rights/tree')
      if (res.meta.status !== 200) {
        this.$message.error('获取用户权限失败')
      }
      this.rightList = res.data
      console.log(this.rightList)
      this.getLeafKeys(role, this.defKeys)
      this.rightDialogState = true
    },
    // 以递归的方式 获取已选中的树形节点
    getLeafKeys (node, arr) {
      console.log(node)
      // 当前节点不是三级节点
      if (!node.children) {
        return arr.push(node.id)
      }

      // 递归实现二级菜单与一级菜单
      node.children.forEach(item =>
        this.getLeafKeys(item, arr)
      )
    },
    // 监听分配权限对话框关闭事件
    setRightDialogClosed () {
      this.defKeys = []
    },
    // 点击确定按钮同时实现分配权限的功能
    async allotRight () {
      const keys = [
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys()
      ]
      const idStr = keys.join(',')
      const { data: res } = await this.$http.post(`roles/${this.roleId}/rights`, {
        rids: idStr
      })
      if (res.meta.status !== 200) {
        this.$message.error('分配用户权限失败')
      }
      this.getRolesList()
      this.rightDialogState = false
      this.$message.success('分配用户权限成功')
    }
  },
}
</script>

<style lang="less">
.bdtop {
  border-top: 1px solid #eee;
}
.bdbot {
  border-bottom: 1px solid #eee;
}
.el-tag {
  margin: 7px;
}
.vcenter {
  display: flex;
  align-items: center;
}
</style>
